package org.lanettiesso.loader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 模拟tomcat。。。
 * <p>
 * BootstrapClassLoader
 * ExtClassLoader
 * AppClassLoader
 * SharedClassLoader
 * WebappClassLoader
 */
public class BootStrap {

    private final ClassLoader sharedClassLoader;

    private final String home;

    private final List<Webapp> webappList = new ArrayList<>();

    public BootStrap(String home) throws IOException, ClassNotFoundException {
        this.home = home;
        sharedClassLoader = new SharedClassLoader(home);
        loadWebapps();
    }

    private void loadWebapps() throws IOException, ClassNotFoundException {
        File webappClazzDir = new File(home + "/webapp");
        File[] files = webappClazzDir.listFiles();
        if (files != null) {
            for (File file : files) {
                Properties properties = new Properties();
                properties.load(new FileInputStream(file.getPath() + "/web.properties"));
                String servletClazz = properties.getProperty("servlet");
                WebappClassLoader webappClassLoader = new WebappClassLoader(file.getName(), home, sharedClassLoader);
                Webapp webapp = new Webapp(webappClassLoader, file.getPath(), servletClazz);
                webappList.add(webapp);
            }
        }
    }


    public static void main(String[] args) throws ClassNotFoundException, IOException {
        String home = "/Users/lan/IdeaProjects/classloader/home";
        BootStrap bootStrap = new BootStrap(home);
        System.out.println(bootStrap.webappList);
        Webapp webapp1 = bootStrap.webappList.get(0);
        Webapp webapp2 = bootStrap.webappList.get(1);
        System.out.println(webapp1.getServletClazz() == webapp1.getClassLoader().loadClass(webapp1.getClazz()));
        System.out.println(webapp1.getServletClazz().getClassLoader());
        try {
            webapp1.getClassLoader().loadClass(webapp2.getClazz());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            bootStrap.sharedClassLoader.loadClass(webapp2.getClazz());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
